package ua.cs.stu.ics.xml;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import ua.cs.stu.ics.label.JLabelExtended;
import ua.cs.stu.ics.utils.Util;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 26.02.11
 * Time: 21:56
 * To change this template use File | Settings | File Templates.
 */
public class Dom4jReader {

    private Document document;

    private void parse(String path){
        File file = new File(path);
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void load(String path, JPanel jPanel){
        parse(path);
        ArrayList<Component> compList = Util.getAllComponents(jPanel);


        for (Component component : compList) {
            if (component instanceof JLabelExtended) {
                if (((JLabelExtended) component).getName() == null)
                    continue;
                Node node = document.selectSingleNode( "//root/"+((JLabelExtended) component).getName() );
                if (node == null)
                    continue;
                int x = Integer.parseInt(((Element) node).attribute("x").getData().toString());
                int y = Integer.parseInt(((Element)node).attribute("y").getData().toString());
                Attribute el = ((Element) node).attribute("text");
                if (el != null){
                    String text = el.getData().toString();
                    ((JLabelExtended) component).setText(text);
                }


                ((JLabelExtended) component).setLocation(x, y);
            }
        }
    }
}
